package com.company.cloud.ad.modules.mgr.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.ad.modules.base.entity.AdInfo;
import com.company.cloud.ad.modules.base.entity.AdPositionInfo;
import com.company.cloud.ad.modules.base.entity.AdPositionRelInfo;
import com.company.cloud.ad.modules.base.service.AdInfoService;
import com.company.cloud.ad.modules.base.service.AdPositionInfoService;
import com.company.cloud.ad.modules.base.service.AdPositionRelInfoService;
import com.company.cloud.ad.modules.cache.models.AdModel;
import com.company.cloud.ad.modules.cache.util.AdConvertUtils;
import com.company.cloud.ad.modules.mgr.controller.req.AdMgrAllocationParam;
import com.company.cloud.ad.modules.mgr.controller.req.AdMgrQuery4PageParam;
import com.company.cloud.ad.modules.mgr.controller.req.AdMgrSaveParam;
import com.company.cloud.ad.modules.mgr.controller.req.AdMgrUpdateParam;
import com.company.cloud.ad.modules.mgr.service.AdMgrService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 广告管理
 */
@Authc
@RestController
@RequestMapping("/mgr/ad")
@Api(tags="Mgr_Ad_广告管理")
public class AdMgrController {

	@Autowired
	private AdPositionInfoService adPositionInfoService;
	@Autowired
	private AdPositionRelInfoService adPositionRelInfoService;
	@Autowired
	private AdInfoService adInfoService;
//	@Autowired
//	private AdCacheService adCacheService;
	@Autowired
	private AdMgrService adMgrService;
	
	@PostMapping("/query")
	@ApiOperation(value="广告信息查询", response= AdModel.class)
	public BaseResult query(@RequestBody AdMgrQuery4PageParam params) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		String inSQL=null;
		if(CheckUtils.hasInt(params.getAdPositionId())) {
			inSQL=StrUtil.format("select ad_id from cms_ad_position_rel_info where ad_position_id={}", params.getAdPositionId());
		}
		IPage<AdInfo> page = adInfoService.page(new Page<>(params.getPage(), params.getRows()),
			new QueryWrapper<AdInfo>()
				.eq(StringUtils.hasText(params.getCompanyNo()), "company_no", params.getCompanyNo())
				.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
				.inSql(CheckUtils.hasInt(params.getAdPositionId()), "id", inSQL)
				.like(StringUtils.hasText(params.getTitle()), "title", params.getTitle())
				.eq(StringUtils.hasText(params.getContentType()), "content_type", params.getContentType())
				.orderByDesc("orders")
				);
		
		if(page==null || CollectionUtils.isEmpty(page.getRecords())) {
			return BaseResult.ok();
		}
		
		//
		Set<Integer> adIds=new HashSet<Integer>();
		page.getRecords().forEach(item->{
			adIds.add(item.getId());
		});
		List<AdPositionRelInfo> relList=adPositionRelInfoService.list(
				new QueryWrapper<AdPositionRelInfo>().in("ad_id", adIds));
		
		//
		List<AdPositionInfo> positionList= adPositionInfoService.list(new QueryWrapper<AdPositionInfo>()
//				.eq("company_no", userInfo.getCompanyNo())
				.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
//				.inSql("ad_position_no", "")
				);
		Map<String, AdPositionInfo> positionMap=new HashMap<String, AdPositionInfo>();
		if(!CollectionUtils.isEmpty(positionList)) {
			positionList.forEach(item->{positionMap.put(item.getAdPositionNo(), item);});
		}
		
		IPage<AdModel> data=page.convert(new Function<AdInfo, AdModel>() {
			@Override
			public AdModel apply(AdInfo entity) {
				return AdConvertUtils.getAdModel(entity,relList,positionMap);
			}
		});
		return BaseResult.ok(data);
	}
	
	@GetMapping("/get")
	@ApiOperation(value="广告信息详情", response=AdModel.class)
	public BaseResult get(@RequestParam("id")Integer id) {
		AdInfo entity = adInfoService.getById(id);
		if(entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		AdModel data= AdConvertUtils.getAdModel(entity);
		return BaseResult.ok(data);
	}
	
	@PostMapping("/save")
	@ApiOperation(value="广告信息新增", response=AdModel.class)
	public BaseResult save(@RequestBody AdMgrSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		AdInfo entity= adMgrService.add(params, userInfo);
		AdModel data= AdConvertUtils.getAdModel(entity);
		return BaseResult.ok(data);
	}
	
	@PostMapping("/update")
	@ApiOperation(value="广告信息修改")
	public BaseResult update(@RequestBody AdMgrUpdateParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		adMgrService.edit(params, userInfo);
		return BaseResult.ok();
	}
	
	@GetMapping("/delete")
	@ApiOperation(value="广告信息表删除")
	public BaseResult delete(@RequestParam("id")Integer id) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		adMgrService.del(id, userInfo);
		return BaseResult.ok();
	}
	
	@GetMapping("/allocation")
	@ApiOperation(value="根据广告分配广告位")
	public BaseResult allocation(@RequestBody AdMgrAllocationParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		adMgrService.allocation(params, userInfo);
		return BaseResult.ok();
	}
	
	
	
}
